package com.chenglu.android.redpacket;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.MainActivity;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseMvpFragment;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.mine.bean.CollectBean;
import com.chenglu.android.mine.login.LoginActivity;
import com.chenglu.android.redpacket.bean.OpenPacketBean;
import com.chenglu.android.redpacket.bean.PacketBean;
import com.chenglu.android.redpacket.mvp.contract.RedPacketContract;
import com.chenglu.android.redpacket.mvp.presenter.RedPacketPresenter;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.CenterPopupView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author: lyj
 * @Created: by Copyright 2023 6 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：红包的列表
 */
public class RedPacketFragement extends BaseMvpFragment<RedPacketPresenter> implements RedPacketContract.View {


    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;
    @BindView(R.id.ll_loading_no_data)
    LinearLayout llLoadingNoData;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.iv_no_data)
    ImageView ivNoData;
    @BindView(R.id.toolbar_username)
    TextView toolbarUsername;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private PacketAdapter packetAdapter;

    public static RedPacketFragement newInstance() {
        RedPacketFragement redPacketFragement = new RedPacketFragement();
        return redPacketFragement;
    }

    @Override
    protected void initView() {
        mPresenter = new RedPacketPresenter();
        mPresenter.attachView(this);

        initAdapter();
        initRefreshLayout();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_red_packet;
    }

    String aaccessToken;
    @Override
    public void onResume() {
        super.onResume();
        aaccessToken = SPUtils.getString(Constant.AaccessToken, null);
        ImmersionBar.with(this)
                .fitsSystemWindows(false)
                .autoDarkModeEnable(true)
                .fullScreen(true)
                .statusBarDarkFont(true)
                .init();
        if(isLogin){
            mPresenter.getPacketList(getToken(),getMap());
        }else {
            mPresenter.getPacketList(getMap());
        }


    }

    int current = 1;

    public Map<String, String> getMap() {
        Map<String, String> map = new HashMap<>();
        map.put("current", current + "");
        map.put("size", "20");
        return map;
    }

    List<PacketBean.Data.Records> list = new ArrayList<>();


    private void initAdapter() {

        packetAdapter = new PacketAdapter(mContext, list);

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(packetAdapter);
//        commentAdapter.notifyDataSetChanged();

        packetAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.fl_red_packet:
                        if(isLogin){
                            mPresenter.getOpenPacket(aaccessToken, packetAdapter.getData().get(position).getId());
                        }else {
                           login();
                        }

                        break;
                }
            }
        });

    }


    //刷新
    private void initRefreshLayout() {
        smartrefreshlayout.setEnableRefresh(false);
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //id 需要传参过来
                current = 1;
                //需要清空数据再加
                list.clear();
                if(isLogin){
                    mPresenter.getPacketList(getToken(),getMap());
                }else {
                    mPresenter.getPacketList(getMap());
                }


            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                current += 1;
                if(isLogin){
                    mPresenter.getPacketList(getToken(),getMap());
                }else {
                    mPresenter.getPacketList(getMap());
                }

            }
        });
    }

    //打开红包的接口
    @Override
    public void getOpenPacket(OpenPacketBean bean) {
//        ToastUtils.show("弹出对话框");
        showRedPacket(bean);
    }

    @Override
    public void onError(String errMessage) {
        super.onError(errMessage);

    }

    /**
     *
     * @description 更新版本ui
     *
     */


    private void showRedPacket(OpenPacketBean bean) {

        RedPacketPopup   redPacketPopup = new RedPacketPopup(getActivity());
        redPacketPopup.setOpenPacketBean(bean);
        new XPopup.Builder(getActivity())
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asCustom(redPacketPopup)
                .show();

    }

    @Override
    public void getPacketList(PacketBean bean) {

        stopRefresh(smartrefreshlayout);

        if(bean.getData().getTotal()>0){
            llLoadingData.setVisibility(View.VISIBLE);
            llLoadingNoData.setVisibility(View.GONE);
            for (int i = 0; i <bean.getData().getRecords().size() ; i++) {
                list.add(bean.getData().getRecords().get(i));
            }

            if(bean.getData().getTotal() < Constant.SIZE){
                smartrefreshlayout.setEnableRefresh(false);
            }
            if(current *Constant.SIZE > bean.getData().getTotal()){
                smartrefreshlayout.setEnableLoadMore(false);
                View inflate = Global.inflate(R.layout.loadmore_addfooter_layout);
                inflate.findViewById(R.id.tv_no_more).setBackgroundColor(getResources().getColor(R.color.color_f6f6f6));
                packetAdapter.addFooterView(inflate);
            }

        }else {
            llLoadingData.setVisibility(View.GONE);
            llLoadingNoData.setVisibility(View.VISIBLE);
        }

        packetAdapter.notifyDataSetChanged();
    }


    class RedPacketPopup extends CenterPopupView {
        //注意：自定义弹窗本质是一个自定义View，但是只需重写一个参数的构造，其他的不要重写，所有的自定义弹窗都是这样。
        public RedPacketPopup(@NonNull Context context) {
            super(context);
        }

        // 返回自定义弹窗的布局
        @Override
        protected int getImplLayoutId() {
            return R.layout.dialog_red_packet;
        }

        // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
        @Override
        protected void onCreate() {
            super.onCreate();

            TextView tvPrice = findViewById(R.id.tv_price);
            ImageView imageView = findViewById(R.id.iv_delete);

            tvPrice.setText(openPacketBean.getData().getMoney()+"");

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

        }

        // 设置最大宽度，看需要而定，
        @Override
        protected int getMaxWidth() {
            return super.getMaxWidth();
        }

        // 设置最大高度，看需要而定
        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        // 设置自定义动画器，看需要而定
        @Override
        protected PopupAnimator getPopupAnimator() {
            return super.getPopupAnimator();
        }

        /**
         * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
         *
         * @return
         */
        protected int getPopupWidth() {
            return 0;
        }

        /**
         * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
         *
         * @return
         */
        protected int getPopupHeight() {
            return 0;
        }

        public OpenPacketBean getOpenPacketBean() {
            return openPacketBean;
        }

        public void setOpenPacketBean(OpenPacketBean openPacketBean) {
            this.openPacketBean = openPacketBean;
        }

        private OpenPacketBean openPacketBean;


    }

}
